package com.kanshu.ksgb.fastread.doudou.module.message.presenter;

import android.os.Handler;
import android.os.Looper;

import com.kanshu.ksgb.fastread.doudou.base.basemvp.BaseMvpPresenter;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.MessageBean;
import com.kanshu.ksgb.fastread.doudou.common.util.ThreadPoolUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;

import java.util.List;

import io.reactivex.subjects.Subject;

/**
 * Created by wcy on 2017\6\26 0026.
 */

public class MessagePresenter extends BaseMvpPresenter<MessageView> {
    int mPage;
    int mTotalPage;
    Handler  mHandler = new Handler(Looper.getMainLooper());
    MessagePageLoader mLoader = new MessagePageLoader();
    public MessagePresenter(Subject<Integer> subject) {
        super(subject);
        calcTotalPage();
        mPage = mTotalPage - 1;
    }

    public int calcTotalPage() {
        mTotalPage = mLoader.getTotalpage();
        return mTotalPage;
    }

    public void loadPageInfo() {
        mPage = mTotalPage - 1;
        loadPageInfo(mPage);
    }

    private void loadPageInfo(final int page) {
        ThreadPoolUtil.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                final List<MessageBean> list = mLoader.loadPage(page);
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (!isViewAttached()) {
                            return;
                        }
                        mMvpView.dismissLoading();
                        if (!Utils.isEmptyList(list)) {
                            mMvpView.showContent(list);
                        } else if (mPage == mTotalPage - 1) {
                            mMvpView.showError(-1, "no data");
                        }
                    }
                });
            }
        });
    }

    public void controlPage() {
        if (mPage <= 0) {
            mMvpView.loadComplete();
        } else {
            mPage--;
            loadPageInfo(mPage);
        }
    }

    @Override
    public void detachView() {
        super.detachView();
    }
}
